package com.mx.tool.form.window.other;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mx.tool.util.NotifyUtil;
import com.mx.tool.result.MobileResult;
import com.mx.tool.result.R;
import org.apache.commons.lang3.StringUtils;

import javax.swing.*;

/**
 * @Author: 徐建鹏.
 * @create: 2021-11-10 19:34
 * @Description:
 */
public class MobileWindow {
    private JPanel jPanel;
    private JTextArea textArea;
    private JTextField textField;
    private JButton queryButton;
    private final Gson gson = new GsonBuilder().setPrettyPrinting().create();

    public JPanel getContent() {
        return jPanel;
    }

    public MobileWindow() {
        queryButton.addActionListener(e -> {
            String mobile = textField.getText();
            if (StringUtils.isBlank(mobile)) {
                NotifyUtil.error("请输入手机号");
                return;
            }
            R result = getMobileInfo(mobile);
            textArea.setText(gson.toJson(result));
        });
    }

    private R getMobileInfo(String mobile) {
        String resultStr = HttpUtil.createPost("https://www.baifubao.com/callback?cmd=1059&callback=phone&phone=" + mobile).execute().body();
        if (StringUtils.isBlank(resultStr)) {
            return R.craate().code("-50").msg("手机号查询失败");
        }
        resultStr = resultStr.replace(")", "");
        resultStr = resultStr.replace("phone(", "");
        JSONObject jsonObject = JSONObject.parseObject(resultStr);
        if (jsonObject == null) {
            return R.craate().code("-50").msg("手机号查询失败");
        }
        JSONObject dataJson = jsonObject.getJSONObject("data");
        if (dataJson == null) {
            return R.craate().code("-50").msg("手机号查询失败");
        }
        MobileResult mobileResult = new MobileResult();
        mobileResult.setMobile(mobile);
        mobileResult.setArea(dataJson.getString("area_operator"));
        return R.craate().code("0").msg("查询成功").data(mobileResult);
    }
}
